<template>
  <section class="component letter-batch-print">
    <!-- 数据列表处理 -->
    <data-box :data="dataSet">
      <template slot="columns">
        <el-table-column prop="caseNumber" label="借据号" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="contName" label="客户姓名" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column label="操作" :min-width="$helper.getColumnWidth(4)">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="removeContact(scope)">移出</el-button>
          </template>
        </el-table-column>
      </template>
    </data-box>

    <!-- 信函模板选择 -->
    <div style="margin-top:20px">
      <el-form :model="model" ref="form" label-width="75px">
        <el-form-item label="逾期阶段" prop="overduePeriod" :rules="{required: true, message: '请选择逾期阶段', trigger: 'blur'}">
          <el-select v-model="model.overduePeriod" placeholder="请选择" clearable @change="onOverduePeriodChange">
            <el-option v-for="{index,name,code} in $dict.getDictData('OverduePeriodStatus')" :key="index" :label="name" :value="code.replace(/\+/, '')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateId" :rules="{required: true, message: '请选择模板', trigger: 'blur'}">
          <el-select v-model="model.templateId" placeholder="请选择" clearable @change="onTemplateChange">
            <el-option v-for="item in templateSet" :key="item.id" :label="item.templateName" :value="item.id"></el-option>
          </el-select>
          <el-button v-if="model.templateId" type="text" @click="dialog.printPreview = true">预览</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="operate-buttons">
      <el-button @click="close()">取消</el-button>
      <el-button @click="submit()">打印</el-button>
    </div>

    <!-- 预览弹窗 -->
    <el-dialog :visible.sync="dialog.printPreview" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body  width="900px">
      <div class="print-preview" style="text-align:left">
        <div v-html="templateContent"></div>
      </div>
    </el-dialog>
  </section>
</template>


<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component';
import { Dependencies } from '~/core/decorator';
import { Emit, Prop, Model} from 'vue-property-decorator';
import { State, namespace } from "vuex-class";
import DataBox from "~/components/common/data-box.vue";
import { SmartCollectionService } from "~/services/domain-service/smart-collection.service";
import { TemplateService } from '~/services/domain-service/template.service';
import { KeyResource } from '~/components/template-manage/letter-template/letter-template.config'
import { CommonService } from "~/utils/common.service";

@Component({
  components: {
    DataBox,
  }
})
export default class LetterBatchPrint extends Vue {
  @Dependencies(SmartCollectionService)
  private smartCollectionService: SmartCollectionService
  @Dependencies(TemplateService)
  private templateService: TemplateService
  @Prop()
  private selectionList: any[]
  private templateSet: any[] = []

  private dataSet: any[] = []

  private templateContent: any = ''
  // 最终要打印的内容
  private printContent: any = ''
  private printPageHeight: number = 0

  private model: any = {
    overduePeriod: '',
    templateId: '',
  }

  private dialog: any = {
    printPreview: false,
  }

  public refreshData() {
    const form: any = this.$refs['form']
    form.resetFields()
    this.loadingData()
    this.printPageHeight = this.getPrintPageHeight()
  }

  @Emit('close')
  private close() {}

  private loadingData() {
    const request: any = {
      ids: this.selectionList.map(v => v.id)
    }
    this.smartCollectionService.getMailPersonal(request).subscribe(
      data => this.dataSet = data || []
    )
  }

  /**
   * 逾期阶段改变
   */
  private onOverduePeriodChange(overduePeriod: string) {
    if (overduePeriod) {
      this.templateService.getTemplateByOverduePeriod({overduePeriod, templateCategory: 'LETTER'}).subscribe(
        data => this.templateSet = data || []
      )
    } else {
      this.model.overduePeriod = ''
    }
    this.onTemplateChange('')
  }

  /**
   * 模板改变
   */
  private onTemplateChange(templateId: string) {
    let templateContent: string = ''
    if (templateId) {
      const template: any = this.templateSet.find(v => v.id === templateId)
      templateContent = template.templateContent
    }
    this.model.templateId = templateId
    // 处理预览的数据
    this.templatePreview(templateContent)
    // 处理要打印的数据
    let contentStr: any = ''
    this.dataSet.forEach((val, index) => {
      let batchContent = `<div style="width:100%;height:${this.printPageHeight}px">` + templateContent + '</div>'
      KeyResource.forEach(v => {
        const tempValue = v.value.substr(1)
        batchContent = batchContent.replace(new RegExp('\\' + v.value, 'g'), val[tempValue])
      })
      contentStr += batchContent
      this.printContent = contentStr
    })
  }

  /**
   * 移除联系人
   */
  private removeContact(scope: any) {
    const index: number = scope.$index
    this.dataSet.splice(index, 1)
  }

  /**
   * 预览数据处理
   */
  private templatePreview(templateContent: any) {
    let val: any = templateContent
    KeyResource.forEach(v => {
      val = val.replace(new RegExp('\\' + v.value, 'g'), '_____________')
    })
    this.templateContent = val
  }

  /**
   * 一键打印
   */
  private submit() {
    if (this.dataSet.length === 0) {
      this.$message.info('数据为空，不能打印')
      return
    }
    const form: any = this.$refs['form']
    form.validate(v => {
      if (!v) return
      const nWindow: any = window.open('.')
      nWindow.document.write(this.printContent)
      nWindow.print()
      nWindow.close()
    })
  }

  /**
   * 打印页高度
   */
  private getPrintPageHeight() {
    const type: any = CommonService.getBrowserType()
    let printPageHeight: number = 0
    switch(type) {
      case 'chrome':
      case 'opera':
        printPageHeight = 1025
        break
      case '360':
        printPageHeight = 1015
        break
      case 'firefox':
        printPageHeight = 1050
        break
      default:
        break
    }
    return printPageHeight
  }

}
</script>

<style lang="less" scoped>
.component.letter-batch-print {
  .print-preview {
    border: solid 1px gray;
    padding: 50px 20px; // margin: 20px 15%;
    height: 297mm;
    width: 210mm;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3), 0 8px 16px rgba(0, 0, 0, 0.5);
    margin: 0 auto;
  }
}
</style>


